<?php
declare (strict_types = 1);

namespace app\admin\model;

use app\common\model\Article\ArticleWithLabels;
use think\db\exception\PDOException;
use think\facade\Db;

/**
 * @mixin \think\Model
 */
class Articles extends \app\common\model\Article\Articles
{
    public function add(array $params = [])
    {
        Db::startTrans();
        try {
            $article = $this->create($this->setFilterFields($params));
            // 关联标签
            $this->setLabels($article->article_id, $params);

            $this->setError('插入成功!');
            Db::commit();
            return true;
        } catch (PDOException $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    public function edit(array $params = [], array $where = [])
    {
        Db::startTrans();
        try {
            $article_id = intval($params[$this->pk]);
            // 更新文章
            $this->where($this->pk, $article_id)->update($this->setFilterFields($params));
            // 关联标签
            $this->setLabels($article_id, $params);

            $this->setError('更新成功!');
            Db::commit();
            return true;
        } catch (PDOException $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 设置关联标签
     *
     * @param $article_id
     * @param $params
     *
     * @return bool
     */
    private function setLabels(int $article_id ,array $params)
    {
        // 删除所有的关联
        ArticleWithLabels::where('article_id', $article_id)->whereNotIn('label_id', $params['label_ids'] ?? [])->delete();

        if (isset($params['label_ids'])){
            foreach ($params['label_ids'] as $label_id){
                if (
                    !ArticleWithLabels::where([
                        'article_id' => $article_id,
                        'label_id' => $label_id
                    ])->find()
                ){
                    // 新增关联
                    ArticleWithLabels::create([
                        'article_id' => $article_id,
                        'label_id' => $label_id
                    ]);
                }
            }
        }
    }
}
